import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:bear_story/views.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../bean/beans.dart';
import '../net.dart' as net;
import '../main.dart';
import 'package:bear_story/dialog.dart';
import 'player.dart';
import 'package:bear_story/views.dart';
import 'login.dart';

class BookPage extends StatefulWidget {
  final Book book;

  BookPage(this.book) : assert(book != null);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _BookPageState(book);
  }
}

class _BookPageState extends State<BookPage> with PlayChaptersUpdateListener {
  final Book book;
  int page = 1;
  final pageSize = 20;
  List<Chapter> chapters = [];
  ScrollController scrollController = ScrollController();

  _BookPageState(this.book);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print("book--initState");
    scrollController.addListener(() {
      if (scrollController.offset == scrollController.position.maxScrollExtent) {
        if (!book.isBear() && chapters.length < book.chapterCount) {
          showToast("正在加载更多数据...", context);
          loadMore();
        }
      }
    });
    addHistoryBook(book);
    refresh();
    if (book.chapterCount <= 0 || book.playCount <= 0) {
      refreshBookExtraInfo([book]).then((v) {
        setState(() {});
      });
    }
    addPlayChaptersUpdateListener(this);
  }

  @override
  void dispose() {
    super.dispose();
    print("book--dispose");
    removePlayChaptersUpdateListener(this);
  }

  List<Widget> getListView() {
    List<Widget> list = [];
    for (int i = 0; i < chapters.length; i++) {
      Chapter chapter = chapters[i];
      Chapter now = getNowPlayChapter();
      if (chapter.pic == null || chapter.pic.length == 0) {
        chapter.pic = book.pic;
      }
      bool isPlaying = false;
      if (now != null) {
        isPlaying = now.objectId == chapter.objectId;
      }
      bool locked = i >= 3 && book.price > 0;
      list.add(GestureDetector(
        onTap: () {
          print("book---onTap isPlaying=$isPlaying");
          setState(() {
            if (!isPlaying) {
              playList(chapters, i, book, true);
            }
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return PlayerPage();
            }));
          });
        },
        child: ChapterListItemView(
          chapter,
          isPlaying,
          locked: locked,
        ),
      ));
    }
    return list;
  }

  bool isInCollect() {
    bool result = false;
    var collects = getNowUserCollects();
    if (collects == null) {
      return false;
    }
    collects.forEach((e) {
      if (e.objectId == book.objectId) {
        result = true;
        return;
      }
    });
    return result;
  }

  Future refresh() async {
    await _requestChapters(true);
  }

  Future _requestChapters(bool isRefresh) async {
    int p = isRefresh ? 1 : page + 1;
    var list = await getChapters(book, p, pageSize);
    if (list != null) {
      page = p;
      if (isRefresh) {
        chapters.clear();
      }
      setState(() {
        chapters.addAll(list);
      });
    }
  }

  Future loadMore() async {
    await _requestChapters(false);
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    bool isCollect = isInCollect();
    return Scaffold(
      appBar: null,
      body: RefreshIndicator(
          color: main_theme_color,
          onRefresh: refresh,
          child: Container(
            constraints: BoxConstraints.expand(),
            child: Stack(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(bottom: play_controller_bar_height),
                  color: Colors.white,
                  child: CustomScrollView(
                    controller: scrollController,
                    slivers: <Widget>[
                      SliverAppBar(
                        backgroundColor: main_theme_color,
//                        pinned: true,//是否固定在顶部
                        floating: true,
                        //是否随着滑动隐藏标题
//                        snap: false,//与floating结合使用
                        elevation: 0,
//                        title: Text(book.bookname),
                        centerTitle: true,
                        actions: <Widget>[
//                      IconButton(icon: Icon(Icons.share), onPressed: () {})
                        ],
                        expandedHeight: banner_height,
                        flexibleSpace: FlexibleSpaceBar(
//                          title: Container(
//                            padding: EdgeInsets.symmetric(horizontal: 49),
//                            child: Text(
//                              book.bookname,
//                              maxLines: 1,
//                              overflow: TextOverflow.ellipsis,
//                            ),
//                          ),
                          centerTitle: true,
                          background: Stack(
                            children: <Widget>[
                              Container(
                                constraints: BoxConstraints.expand(),
                                child: CachedNetworkImage(
                                  placeholder: (context, url) {
                                    return Container(
                                      color: Color(0xffefeff4),
                                    );
                                  },
                                  imageUrl: book.pic,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              Align(
                                alignment: FractionalOffset.bottomCenter,
                                child: Container(
                                  constraints: BoxConstraints.expand(height: main_radius),
                                  height: main_radius,
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.only(
                                          topLeft: Radius.circular(main_radius),
                                          topRight: Radius.circular(main_radius))),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                      SliverList(
                          delegate: SliverChildListDelegate([
                        Padding(
                          padding: EdgeInsets.only(
                              top: main_padding_top - main_radius, left: main_padding_left, right: main_padding_left),
                          child: Row(
                            children: <Widget>[
                              Text(
                                book.bookname,
                                style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold, color: Color(0xff333333)),
                              ),
                              Expanded(
                                child: Container(),
                              ),
                              GestureDetector(
                                onTap: () {
                                  if (isCollect) {
                                    showLoadingDialog(context);
                                    net.removeCollect(getNowUser().objectId, book.objectId).then((v) {
                                      updateNowUserCollects().then((v) {
                                        Navigator.of(context).pop();
                                        setState(() {});
                                      });
                                    });
                                  } else {
                                    if (getNowUser() == null) {
                                      pushPage(context, LoginPage()).then((value) {
                                        updateNowUserCollects().then((v) {
                                          setState(() {});
                                        });
                                      });
                                    } else {
                                      showLoadingDialog(context);
                                      net.addCollect(getNowUser().objectId, book.objectId).then((v) {
                                        updateNowUserCollects().then((v) {
                                          Navigator.of(context).pop();
                                          setState(() {});
                                        });
                                      });
                                    }
                                  }
                                },
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(
                                      isCollect ? Icons.favorite : Icons.favorite_border,
                                      size: 17,
                                      color: isCollect ? main_theme_color : Color(0xff666666),
                                    ),
                                    Text(
                                      "收藏",
                                      style: TextStyle(
                                          fontWeight: FontWeight.w300, fontSize: 14, color: Color(0xff666666)),
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 7, left: main_padding_left, right: main_padding_left),
                          child: Text(
                            book.bookdes,
                            style: TextStyle(fontSize: 13, color: Color(0xff666666), fontWeight: FontWeight.w300),
                          ),
                        ),
                        Padding(padding: EdgeInsets.only(top: main_padding_top)),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              constraints: BoxConstraints.expand(height: 28, width: 114),
                              decoration: BoxDecoration(
                                image: DecorationImage(image: AssetImage("images/album_bq.png"), fit: BoxFit.fill),
                              ),
                              child: Padding(
                                padding: EdgeInsets.only(left: main_padding_left),
                                child: Align(
                                  alignment: FractionalOffset.centerLeft,
                                  child: Text(
                                    "更新至${book.chapterCount}集",
                                    style: TextStyle(fontSize: 13, fontWeight: FontWeight.w300, color: Colors.white),
                                  ),
                                ),
                              ),
                            ),
                            Expanded(
                              child: Container(),
                            ),
                            Icon(
                              Icons.play_circle_outline,
                              color: Color(0xff999999),
                              size: 15,
                            ),
                            Padding(
                              padding: EdgeInsets.only(left: 2, right: main_padding_left),
                              child: Text(
                                "${getPlayCountStr(book.playCount)}次播放",
                                style: TextStyle(fontWeight: FontWeight.w300, fontSize: 13, color: Color(0xff999999)),
                              ),
                            ),
                          ],
                        ),
                        Divider(
                          height: 1,
                          color: Color(0xFFdddddd),
                        )
                      ])),
                      SliverFixedExtentList(delegate: SliverChildListDelegate(getListView()), itemExtent: 120)
                    ],
                  ),
                ),
                Align(
                  alignment: AlignmentDirectional.bottomCenter,
                  child: PlayerControllerBarView(),
                )
              ],
            ),
          )),
    );
  }

  @override
  void onPlayChaptersUpdate() {
    // TODO: implement onPlayChaptersUpdate
    setState(() {});
  }
}
